package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.exception.TokenException;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class Tokenterceptor implements HandlerInterceptor {
    // @Autowired
    // private EmploeeMapper emploeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("AuthorizationUser");
        //hasTest有没有内容
    if (!StringUtils.hasText(token)){
        throw  new TokenException();
    }
        String user = (String) redisTemplate.opsForValue().get("user_token:" + token);
        User newUser = JSON.parseObject(user, User.class);

        if (newUser ==null){
            throw  new TokenException();
        }
        ThreadLocalIUtil.setId(newUser.getId());
        redisTemplate.opsForValue().set("user_token:"+token,JSON.toJSONString(newUser));
        return true;

    }
}
